import KoaRouter from 'koa-router'
import API from '../api'
import middleware from '../middleware'
import qr from 'qr-image'

import {
  getServerAddress,
  getProjectDir,
  saveMemoryToDisk,
  compileToBundle,
  readBundleFile
} from '../service'

/**
 * 二维码生成
 */
async function index (context, next) {
  const port = context.app.server.address().port
  const prefix = getServerAddress(port)
  const data = `${prefix}/api/hapBundle/${context.params.key}`
  const image = qr.image(data, {
    size: 9
  })
  context.type = 'image/png'
  context.body = image
  await next()
}

/**
 * 下载rpk
 */
async function hapBundle (context, next) {
  const key = context.params.key
  if (!key) {
    context.throw(403, `key不存在`)
  }
  try {
    const result = await readBundleFile(key)
    await next()
    context.type = 'text/plain'
    context.body = result
  } catch (e) {
    context.throw(404, `无法找到项目的rpk文件`)
  }
}

/**
 * 加载文件
 */
async function loadDirectory (context, next) {
  const key = context.query.key
  if (!key) {
    context.throw(404, `key不存在`)
  }
  try {
    const data = {
      dir: await getProjectDir(key)
    }
    await next()
    context.type = 'application/json'
    context.body = {
      code: 200,
      message: `加载${key}文件夹成功`,
      data
    }
  } catch (e) {
    context.throw(500, `${key}读取文件目录发生错误`)
  }
}

/**
 * 保存文件
 */
async function saveDirectory (context, next) {
  const contentLength = context.request.header['content-length']
  if (contentLength >> 0 > 5 * 1024 * 1024) {
    context.throw(413, `内容过大，不允许上传`)
  }
  const body = context.request.body
  if (!body.key) {
    context.throw(403, `key不存在`)
  }
  try {
    await saveMemoryToDisk(body.key, body.memFs)
    await next()
    context.type = 'application/json'
    context.body = {
      code: 200,
      message: `保存成功`
    }
  } catch (e) {
    context.throw(500, `${body.key}保存发生错误`)
  }
}

/**
 * 项目编译
 */
async function hapBuild (context, next) {
  const body = context.request.body
  if (!body.key) {
    context.throw(403, `key不存在`)
  }
  try {
    const result = await compileToBundle(body.key)
    await next()
    context.type = 'application/json'
    context.body = {
      code: 200,
      message: result.stdout
    }
  } catch (e) {
    // 用于处理错误信息
    const $err_a = e.message.replace(/\/memfs\/hap\/demo\//ig, '$$project_root').replace(/(\/[\w|-]+)+\/src/ig, '').split('throw new Error(err)')
    context.throw(500, ($err_a && $err_a[1]) || `编译${body.key}发生错误`)
  }
}

function applyRouter(app) {
  app.use(middleware.logger)
  app.use(middleware.errorHandler)

  const router = new KoaRouter()
  // 路由对应控制器
  router.get(API.index, index)
  router.get(API.hapBundle, hapBundle)
  router.get(API.loadDirectory, loadDirectory)
  router.post(API.saveDirectory, saveDirectory)
  router.post(API.hapBuild, hapBuild)
  return router
}

module.exports = {
  applyRouter
}